package com.ljy.my_study.java.juc.lock.readwritelock;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReadWriteLockTestMain2 {

    public static void main(String[] args) {
        Cache cache=new Cache();
        Runnable runnable=()->{
            System.out.println(Thread.currentThread().getName()+"-"+cache.get("id"));
        };
        for(int i=0;i<10;i++){
            new Thread(runnable).start();
        }
    }

    static class Cache{

        private Map<String,Object> map=new HashMap<>();

        private ReentrantReadWriteLock lock=new ReentrantReadWriteLock();

        public Object get(String key){
            Object value=null;
            try{
                lock.readLock().lock();
                value=map.get(key);
                if(value==null){
                    //获取写锁之前需要释放读锁
                    lock.readLock().unlock();
                    try{
                        lock.writeLock().lock();
                        value=map.get(key);
                        if(value==null){
                            System.out.println(Thread.currentThread().getName());
                            value=Math.random();
                            map.put(key,value);
                        }
                        //锁降级
                        lock.readLock().lock();
                    }finally {
                        lock.writeLock().unlock();
                    }
                }
            }finally {
                lock.readLock().unlock();
            }
            return value;
        }

    }
}
